import BaseComponent from "../../Game/Base/BaseClass/BaseComponent";
import FPJDefine from "../../Game/FPJ/Prefabs/FPJDefine";
import ScrollViewPlus from "../../lib/ScrollViewPlus";
import { GCtrl } from "../../lib/util/GCtrl";
import LoadingDialog from "./LoadingDialog";
import TableItemPrefab, { TableItemData } from "./TableItemPrefab";
import TableItemTypePrefab, { TableItemTypeData } from "./TableItemTypePrefab";
import RoomBtn from "../RoomBtn/RoomBtn";
const { ccclass, property } = cc._decorator;

@ccclass
export default class ScrollViewVisiableAreaRenderCtrl extends BaseComponent {

	@property(cc.Node)
	RoomBtnNode: cc.Node = null;

	@property(cc.Prefab)
	RoomBtnPre: cc.Prefab = null;

	@property(ScrollViewPlus)
	scrollViewPlus: ScrollViewPlus = null;

	@property(cc.Prefab)
	scrollViewItemPrefab: cc.Prefab = null;

	@property(cc.Prefab)
	scrollViewTypeItemPrefab: cc.Prefab = null;

	@property(LoadingDialog)
	loadingDialog: LoadingDialog = null;


	_alltable = [];

	_currentRoomLevel = 0;
	_RoomBtnCom: RoomBtn = null;
	uiinitover = false;
	onLoad() {
		this.loadingDialog.hide();
		cc.vv.eventCustom.on("TableItemShow", this.TableItemShow.bind(this), this.node);
		cc.vv.eventCustom.on("TableItemHide", this.TableItemHide.bind(this), this.node);
		cc.vv.eventCustom.on("hallTouchRoomBtn", this.hallTouchRoomBtn.bind(this), this.node);
		this.onEvent("ServerNtc");
		cc.vv.eventCustom.on("refreshHallTable", this.refreshHallTable.bind(this), this.node);
		cc.vv.eventCustom.on("bindAgentSucess", () => { //绑定代理成功要刷新一次
			cc.vv.GLUtils.sendRequest("ATTEnterGame", {}, (error, data) => {
				if (!data.errorcode) {
					FPJDefine.resetAllData();
					FPJDefine.room_list = data.room_list; //房间列表
					FPJDefine.player_list = data.player_list;// 玩家列表
					FPJDefine.initAllTable();
					this._RoomBtnCom && this._RoomBtnCom.setRoomBtn();
					this.createAllTable()
				} else {
					cc.vv.GLUtils.showTips(data.errordes);
				}
			});
		}, this.node);

		cc.game.on(
			cc.game.EVENT_SHOW,
			function () {
				console.log("翻牌机检查座子数量");
			}.bind(this)
		);
		this.addRoomBtn();
		this.createAllTable()
	}
	onEnable() {
		cc.vv.audioUtil.playMusic("Hall/FPJTableView/bgm");
		//cc.vv.eventCustom.emit("showsp", this._currentRoomLevel);
		this.setShowSp(this._currentRoomLevel);
	}
	onDisable() {
		cc.vv.audioUtil.stopAll()
	}
	onDestroy() {
		this.offEvent("ServerNtc");
	}
	start() {

	}

	ServerNtc(data) {
		data = data[0];
		let handler_name = "on" + data.cmd;
		if (!this.uiinitover) {
			console.log("ui尚未初始化完毕  消息不处理")
			return;
		}
		cc.log("STC -> FPJ : ", handler_name, " \ndata:", data);
		if (data.cmd == "ATTGameChangeNtc") {  //刷新界面数据
			FPJDefine.ATTGameChange(data)
			var localtabledata = FPJDefine.table_list;
			var servertabledata = [];
			for (var s = 0; s < data.rooms.length; s++) {
				servertabledata = servertabledata.concat(data.rooms[s].table_list)
			}
			let result = this.compareTableData(servertabledata, localtabledata)
			let total = 0;
			for (var t = 0; t < this.scrollViewPlus.content.childrenCount; t++) {
				let p = this.scrollViewPlus.content.children[t];
				if (p.istable) {
					total++;
				}
			}

			let updateNow = data.updateNow;
			if (result["addtable"].length > 0 || result["deletetable"].length > 0 || updateNow) {//服务器数据座子数量有变动 刷新  全部刷新
				console.log("服务器数据座子数量有变动 刷新  全部刷新")
				this.scrollViewPlus.content.removeAllChildren();
				for (var t = 0; t < this.scrollViewPlus.content.childrenCount; t++) {
					this.scrollViewPlus.content.children[t].destroy();
				}
				//add by 肖帅
				//this.scrollViewPlus.content.removeAllChildren();
				FPJDefine.initAllTable();
				this.createAllTable()
			} else { //ui座子总数和数据不一致  刷新一次

				let total = 0;
				for (var t = 0; t < this.scrollViewPlus.content.childrenCount; t++) {
					let p = this.scrollViewPlus.content.children[t];
					if (p.istable) {
						total++;
					}
				}
				console.log("total   is ", total, "  var localtabledata = FPJDefine.table_list; ", servertabledata.length)
				if (total != servertabledata.length) { //ui座子总数和数据不一致  刷新一次
					this.scrollViewPlus.content.removeAllChildren();
					for (var m = 0; m < this.scrollViewPlus.content.childrenCount; m++) {
						this.scrollViewPlus.content.children[m].destroy();
					}
					//add by 肖帅
					//this.scrollViewPlus.content.removeAllChildren();
					FPJDefine.initAllTable();
					this.createAllTable()
				}
			}

			//刷新数据
			for (var t = 0; t < this.scrollViewPlus.content.childrenCount; t++) {
				let p = this.scrollViewPlus.content.children[t];
				if (p.istable) {
					let sc = p.getComponent(TableItemPrefab);
					let cunzai = false;
					for (var m = 0; m < servertabledata.length; m++) {
						if (servertabledata[m].table_id == sc._data.tableData.table_id) {
							cunzai = true
							break;
						}
					}
					if (cunzai) {  // 如果这张座子没在服务器中 删除  
						console.log("这张座子在服务器中 更新")
						sc.updataTableData(); // 如果这张座子在服务器中 更新
					} else {
						console.log("这张座子没在服务器中 删除")
						p.removeFromParent();
						p.destroy();
					}
				}
			}
		}
		if (data.cmd == "ATTTableChangeNtc") {  //刷新界面数据
			FPJDefine.ATTTableChange(data)
			for (var t = 0; t < this.scrollViewPlus.content.childrenCount; t++) {
				let p = this.scrollViewPlus.content.children[t];
				if (p.istable) {
					p.getComponent(TableItemPrefab).updataTableData();
				}
			}
		}
	}

	/* 手动刷新大厅桌子 create by tm */
	refreshHallTable(): void {
		this.ServerNtc([{
			cmd: "ATTGameChangeNtc",
			is_ntc: true,
			player_out: [],
			players: FPJDefine.player_list || [],
			rooms: FPJDefine.room_list || [],
			updateNow:true,
		}]);
		this._RoomBtnCom && this._RoomBtnCom.setRoomBtn();
	}
	// 比较坐姿数据 刷新创建和删除坐姿
	compareTableData(servertabledata, localtabledata) {
		var arr1 = JSON.parse(JSON.stringify(servertabledata))
		var arr2 = JSON.parse(JSON.stringify(localtabledata));
		var addarry = [];
		var deletearray = [];
		for (var s = 0; s < arr1.length; s++) {
			var newflag = true
			for (var t = 0; t < arr2.length; t++) {

				if (arr2[t].table_id == arr1[s].table_id) {
					newflag = false;
					break;
				}
			}
			if (newflag) {
				addarry.push(arr1[s])
			}
		}
		for (var s1 = 0; s1 < arr2.length; s1++) {
			var deleteflag = true
			for (var t1 = 0; t1 < arr1.length; t1++) {
				if (arr1[t1].table_id == arr2[s1].table_id) {
					deleteflag = false;
					break;
				}
			}
			if (deleteflag) {
				deletearray.push(arr1[s1])
			}
		}
		console.log("add:", addarry)
		console.log("delete:", deletearray)
		return { "addtable": addarry, "deletetable": deletearray }
	}

	test(arg) {
		this.scrollViewPlus.scrollToOffset(cc.v2(arg[0], 0), 0.2);
	}
	scrolltoOffsetByLevel(level) {
		let s = level;
		let offx = 0;
		//跳转到高级  查找高级的item坐标
		for (var t = 0; t < this.scrollViewPlus.content.childrenCount; t++) {
			let p = this.scrollViewPlus.content.children[t];
			if (p.istable) {
				if (p.getComponent(TableItemPrefab).getData().RoomLevel >= level) {
					offx = p.x - 200;
					break;
				}
			}
		}
		console.log("滚动到s ", s, this.scrollViewPlus.getMaxScrollOffset(), offx)
		this.scrollViewPlus.scrollToOffset(cc.v2(offx, 0), 0.2);
	}

	TableItemShow(args) {

		if (this._currentRoomLevel != args[0].RoomLevel) {
			this._currentRoomLevel = args[0].RoomLevel;
			console.log("显示  table等级改变了。。。", this._currentRoomLevel)
			//cc.vv.eventCustom.emit("showsp", this._currentRoomLevel)
			this.setShowSp(this._currentRoomLevel);
		}
	}
	TableItemHide(args) {
		//最后一个隐藏了 
		if (args[0].tableData.tableid >= FPJDefine.getRoomdataBytableId(args[0].tableData.table_id).table_list.length) {
			console.log("//最后一个隐藏了   ", args[0])
			if (this._currentRoomLevel == args[0].RoomLevel) {
				if (this._currentRoomLevel + 1 <= 2) {
					if (this.checkHaveLevelInScroll(this._currentRoomLevel + 1)) {
						this._currentRoomLevel = this._currentRoomLevel + 1
						//cc.vv.eventCustom.emit("showsp", this._currentRoomLevel)
						this.setShowSp(this._currentRoomLevel);
					}
				}
			}
		}
		if (args[0].tableData.tableid <= 0) {
			console.log("//第一一个隐藏了   ", args[0])
			if (this._currentRoomLevel == args[0].RoomLevel) {
				if (this._currentRoomLevel > 0) {
					if (this.checkHaveLevelInScroll(this._currentRoomLevel - 1)) {
						this._currentRoomLevel = this._currentRoomLevel - 1
						//cc.vv.eventCustom.emit("showsp", this._currentRoomLevel);
						this.setShowSp(this._currentRoomLevel);
					}
				}
			}
		}
	}
	async createAllTable() {
		this.loadingDialog.show();
		this.scrollViewPlus.content.removeAllChildren();
		//cc.vv.eventCustom.emit("showsp", 0)
		this.setShowSp(0);
		let table = JSON.parse(JSON.stringify(FPJDefine.table_list));
		//await this.executePreFrame(this._getItemGenerator(table), 1);
		this._getItemGeneratorXS(table);
		// 在创建好子节点之后，先手动调用一次DC优化，触发当前在可视区域内的节点的进入逻辑
		// 后续的ScrollView滚动时，内部自动回调
		this.scrollViewPlus.optDc();
		//检查自己是否停留在某个座子中
		console.log("开始检查自己是否在某个座子中")
		let data = JSON.parse(JSON.stringify(FPJDefine.player_list))
		for (var s = 0; s < data.length; s++) {
			if (data[s]["rid"] == cc.vv.session.getRid()) {
				let play_now = data[s]["play_now"]
				if (play_now) {
					cc.vv.GLUtils.sendRequest("ATTEnterTable", {
						table_id: play_now
					}, (error, data) => {
						if (!error) {
							if (data.errorcode) {
								cc.vv.GLUtils.showTips(data.errordes);
							} else {
								FPJDefine.setTableDetail(data.table_data);
								FPJDefine.setcurrentTableId(data.table_data.table_id)
								FPJDefine.setCurrentState(data.table_data.status)
								let _path = cc.vv.GLDefine.getEnglishNameById(109);
								cc.vv.UIMgr.open(cc.vv.GLConfig.waiting_path);
								cc.vv.sceneMgr.openScene(_path, data, () => {
									cc.vv.eventCustom.emit("openGame");
									cc.vv.UIMgr.close(cc.vv.GLConfig.waiting_path, cc.vv.UIMgr.closeType.hide);
								});
							}
						}
					});
				}
			}
		}
		this.uiinitover = true;
		this.loadingDialog.hide();
	}

	/**
	 * 分帧执行 Generator 逻辑
	 *
	 * @param generator 生成器
	 * @param duration 持续时间（ms），每次执行 Generator 的操作时，最长可持续执行时长。假设值为8ms，那么表示1帧（总共16ms）下，分出8ms时间给此逻辑执行
	 */
	private executePreFrame(generator: Generator, duration: number) {
		return new Promise((resolve, reject) => {
			let gen = generator;
			// 创建执行函数
			let execute = () => {
				// 执行之前，先记录开始时间
				let startTime = new Date().getTime();

				// 然后一直从 Generator 中获取已经拆分好的代码段出来执行
				for (let iter = gen.next(); ; iter = gen.next()) {
					// 判断是否已经执行完所有 Generator 的小代码段，如果是的话，那么就表示任务完成
					if (iter == null || iter.done) {
						resolve();
						return;
					}

					// 每执行完一段小代码段，都检查一下是否已经超过我们分配的本帧，这些小代码端的最大可执行时间
					if (new Date().getTime() - startTime > duration) {
						// 如果超过了，那么本帧就不在执行，开定时器，让下一帧再执行
						this.scheduleOnce(() => {
							execute();
						});
						return;
					}
				}
			};

			// 运行执行函数
			execute();
		});
	}

	_getItemGeneratorXS(data: { roomid: string; tableid: number; level: number }[]){
		let t = data.length;
		let currentlevel = -1;

		for (let i = 0; i < t; i++) {
			let level = Number(data[i].roomid);
			if (currentlevel != level) {
				let itemNode = cc.instantiate(this.scrollViewTypeItemPrefab);
				itemNode.parent = this.scrollViewPlus.content;
				itemNode.istable = false;
				itemNode.getComponent(TableItemTypePrefab).bindData({
					RoomLevel: level,
				});
				currentlevel = level
			}
			this._initScrollViewItemPrefab({
				tableData: data[i],
				playername: String(i),
				RoomLevel: level,
				type: 1,
			});
		}
		this.scrolltoOffsetByLevel(0);
	}

	private *_getItemGenerator(data: { roomid: string; tableid: number; level: number }[]) {
		let t = data.length;
		let currentlevel = -1;

		for (let i = 0; i < t; i++) {
			let level = Number(data[i].roomid);
			if (currentlevel != level) {
				let itemNode = cc.instantiate(this.scrollViewTypeItemPrefab);
				itemNode.parent = this.scrollViewPlus.content;
				itemNode.istable = false;
				itemNode.getComponent(TableItemTypePrefab).bindData({
					RoomLevel: level,
				});
				currentlevel = level
			}
			yield this._initScrollViewItemPrefab({
				tableData: data[i],
				playername: String(i),
				RoomLevel: level,
				type: 1,
			});
		}
		this.scrolltoOffsetByLevel(0);
	}
	private _initScrollViewItemPrefab(data: TableItemData) {
		let itemNode = cc.instantiate(this.scrollViewItemPrefab);
		itemNode.istable = true;
		itemNode.parent = this.scrollViewPlus.content;
		itemNode.getComponent(TableItemPrefab).bindData(data);
	}

	//进入初级场次
	onClickchoicelowLevel(level) {
		cc.vv.audioUtil.playSound("Hall/sound/button_onclicked");
		this.scrolltoOffsetByLevel(level);
	}
	checkHaveLevelInScroll(level) {
		let have = false;
		for (var t = 0; t < this.scrollViewPlus.content.childrenCount; t++) {
			let p = this.scrollViewPlus.content.children[t]
			if (p && p.istable) { //
				let sc = p.getComponent("TableItemPrefab")
				if (sc && sc._data && sc._data.RoomLevel == level) {
					if (sc.inScrolle) {
						have = true; // 有座子展示在uiscroll中
						break;
					}
				}
			}
		}
		return have;
	}
	setShowSp(level) {
		cc.vv.eventCustom.emit("showsp", level);
		let room_id = FPJDefine.room_list[level] && FPJDefine.room_list[level].room_id;
		//传过去
		this._RoomBtnCom && this._RoomBtnCom.setChoose(room_id);
	}
	addRoomBtn() {
		let roomBtn = cc.instantiate(this.RoomBtnPre);
		roomBtn.setParent(this.RoomBtnNode);
		this._RoomBtnCom = roomBtn.getComponent(roomBtn.name);
	}
	hallTouchRoomBtn(data) {
		let roomid = data[0].roomid;
		let level = 0;
		for (let i in FPJDefine.room_list) {
			if (FPJDefine.room_list[i].room_id == roomid) {
				level = parseInt(i);
			}
		}
		this.onClickchoicelowLevel(level);
	}
}
